<template>
  <div>
    <el-dialog
      v-loading.lock="loading"
      class="base-dialog system-user-dialog"
      :append-to-body="true"
      :title="title"
      align="center"
      :visible.sync="dialogFormVisible"
      @closed="closeDialog"
    >
      <el-form
        ref="formData"
        class="base-pipeline-layout system-user-form"
        label-width="100px"
        :model="formData"
        :rules="formDataRules"
        status-icon
      >
        <el-form-item
          label="仓库编码"
          :label-width="formLabelWidth"
          prop="code"
          :error="errorMsg.code"
        >
          <el-input
            v-model="formData.code"
            autocomplete="off"
            clearable
            maxlength="50"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="仓库名称"
          :label-width="formLabelWidth"
          prop="name"
          :error="errorMsg.name"
        >
          <el-input
            v-model="formData.name"
            autocomplete="off"
            clearable
            maxlength="50"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="仓库地址"
          :label-width="formLabelWidth"
          prop="address"
          :error="errorMsg.address"
        >
          <el-input
            v-model="formData.address"
            autocomplete="off"
            clearable
            maxlength="100"
            show-word-limit
          ></el-input>
        </el-form-item>
        <el-form-item
          label="负责人"
          :label-width="formLabelWidth"
          prop="personLiableId"
        >
          <el-select
            ref="selectPerson"
            v-model="formData.personLiableId"
            :multiple="false"
            filterable
            placeholder="请选择责任人"
            value-key="id"
            @change="selectPersonLiable"
          >
            <el-option
              v-for="item in userOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          label="联系电话"
          :label-width="formLabelWidth"
          prop="contactPhone"
          :error="errorMsg.contactPhone"
        >
          <el-input
            v-model="formData.contactPhone"
            autocomplete="off"
            clearable
            maxlength="11"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="状态"
          :label-width="formLabelWidth"
          prop="status"
          :error="errorMsg.status"
        >
          <el-select v-model="formData.status">
            <el-option label="启用" :value="1" />
            <el-option label="禁用" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item
          label="仓库描述"
          :label-width="formLabelWidth"
          prop="description"
          :error="errorMsg.description"
        >
          <el-input
            v-model="formData.description"
            type="textarea"
            :rows="2"
            autocomplete="off"
            clearable
            maxlength="1000"
            show-word-limit
          ></el-input>
        </el-form-item>
        <el-form-item
          label="仓库类型"
          :label-width="formLabelWidth"
          prop="type"
          :error="errorMsg.type"
        >
          <el-select v-model="formData.type">
            <el-option label="危化品仓库" :value="1" />
            <el-option label="物料仓库" :value="2" />
          </el-select>
        </el-form-item>
      </el-form>
      <div>
        <!-- 管理员 -->
        <el-table :data="formData.keepers" style="width: 100%" max-height="250">
          <el-table-column fixed prop="sysUserId" label="姓名" width="120">
            <template slot-scope="scope">
              <el-select
                ref="selectUser"
                v-model="scope.row.sysUserId"
                :multiple="false"
                filterable
                placeholder="请选择管理员"
                value-key="id"
                @change="(val) => selectKeeper(val, scope.$index)"
              >
                <el-option
                  v-for="item in userOptions"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                ></el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column prop="account" label="工号" width="120">
            <template slot-scope="scope">
              {{ scope.row.sysUserAccount }}
            </template>
          </el-table-column>
          <el-table-column prop="depName" label="部门" width="120">
            <template slot-scope="scope">
              {{ scope.row.sysUserDepName }}
            </template>
          </el-table-column>
          <el-table-column prop="mobile" label="联系方式" width="120">
            <template slot-scope="scope">
              {{ scope.row.sysUserMobile }}
            </template>
          </el-table-column>
          <el-table-column fixed="right" label="操作" width="120">
            <template slot-scope="scope">
              <el-link
                size="mini"
                type="danger"
                @click.native.prevent="deleteRow(scope.$index)"
                >删除</el-link
              >
            </template>
          </el-table-column>
        </el-table>
        <el-button icon="el-icon-plus" style="margin-top: 10px" @click="addRow"
          >添加管理员</el-button
        >
      </div>
      <div slot="footer" class="dialog-footer" align="center">
        <el-button type="primary" @click="onSubmit('formData')"
          >保 存</el-button
        >
        <el-button @click="closeDialog">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getUserListNoPage } from "../../../api/Permission/PermissionUser.js";
import { getById, create, update } from "../../../api/Storage/Storage.js";
export default {
  name: "StorageEdit",
  props: {
    value: {
      type: Boolean,
      default: false,
    },
    editId: {
      type: [String, Number],
      default: "",
    },
  },
  data() {
    return {
      loading: false,
      dialogFormVisible: false,
      formLabelWidth: "100px",
      title: "",
      userOptions: [],
      initData: {
        id: 0,
        name: "",
        code: "",
        address: "",
        personLiableId: "",
        contactPhone: "",
        status: 1,
        type: 1,
        description: "",
        keepers: [],
      },
      formData: {
        id: 0,
        name: "",
        code: "",
        address: "",
        personLiableId: "",
        contactPhone: "",
        status: 1,
        type: 1,
        description: "",
        keepers: [],
      },
      formDataRules: {
        name: [
          {
            required: true,
            trigger: "blur",
            message: "请填写仓库名称",
          },
        ],
        code: [
          {
            required: true,
            trigger: "blur",
            message: "请填写仓库编码",
          },
        ],
        address: [
          {
            required: true,
            trigger: "blur",
            message: "请填写仓库地址",
          },
        ],
        personLiableId: [
          {
            required: true,
            trigger: "change",
            message: "请选择责任人",
            type: "",
          },
        ],
        contactPhone: [
          {
            required: true,
            trigger: "blur",
            validator: this.validatePhone,
          },
        ],
      },
      initErrorMsg: {
        name: "",
        code: "",
        address: "",
        personLiableId: "",
        contactPhone: "",
        status: "",
        type: "",
        description: "",
      },
      errorMsg: {
        name: "",
        code: "",
        address: "",
        personLiableId: "",
        contactPhone: "",
        status: "",
        type: "",
        description: "",
      },
    };
  },
  watch: {
    value: function() {
      this.dialogFormVisible = this.value;
      if (this.value) {
        this.init();
      }
    },
  },
  created() {},
  methods: {
    async init() {
      this.userOptions = [];
      getUserListNoPage({ userStatus: 1 })
        .then((res) => {
          this.userOptions = res.data;
        })
        .catch((res) => {});

      if (this.editId) {
        this.title = "修改仓库";
        this.formData.id = this.editId;
        getById({ id: this.editId })
          .then((res) => {
            if (res.data !== null) {
              this.formData = res.data;
            } else {
              this.formData = {};
            }
          })
          .finally(() => {
            this.formLoading = false;
          });
      } else {
        this.title = "新增仓库";
        this.formData.id = 0;
        this.loading = false;
      }
    },
    selectPersonLiable(val) {
      var obj = {};
      obj = this.userOptions.find(function(i) {
        return i.id === val;
      });
      this.formData.contactPhone = obj.mobile;
    },
    selectKeeper(val, index) {
      var obj = {};
      obj = this.userOptions.find(function(i) {
        return i.id === val;
      });
      this.formData.keepers[index].sysUserAccount = obj.account;
      this.formData.keepers[index].sysUserMobile = obj.mobile;
    },
    addRow() {
      if (this.formData.keepers.length >= 10) {
        this.$message.error("最多设置10个管理员");
        return;
      }
      const obj = {};
      var index = this.formData.keepers.length + 1;
      this.formData.keepers.splice(index, 0, obj);
    },
    deleteRow(index) {
      this.formData.keepers.splice(index, 1);
    },

    closeDialog() {
      this.formData.keepers = [];
      this.$refs.formData.resetFields();
      this.$emit("input", false);
      this.$parent.getList();
    },
    onSubmit() {
      this.$refs.formData.validate((valid) => {
        if (!valid) {
          return false;
        } else {
          // 验证管理员
          if (this.formData.keepers && this.formData.keepers.length > 0) {
            const keeperArrs = this.formData.keepers.map(
              (item) => item.sysUserId
            );
            const isRepeat = keeperArrs.some((item, index, arr) => {
              return arr.indexOf(item) !== index;
            });
            if (isRepeat) {
              this.$message.error("管理员重复");
              return false;
            }
            if (this.formData.keepers.length > 10) {
              this.$message.error("最多设置10个管理员");
              return false;
            }
          }
          this.loading = true;
          this.errorMsg = this.Helper.deepCopy(this.initErrorMsg);
          if (this.editId) {
            update(this.formData)
              .then((res) => {
                if (res.code === 200) {
                  this.closeDialog();
                } else {
                  this.showValidateMsgCheck(res);
                }
                this.loading = false;
              })
              .catch(() => {
                this.loading = false;
              });
          } else {
            create(this.formData)
              .then((res) => {
                if (res.code === 200) {
                  this.closeDialog();
                } else {
                  this.showValidateMsgCheck(res);
                }
                this.loading = false;
              })
              .catch(() => {
                this.loading = false;
              });
          }
        }
      });
    },
    showValidateMsgCheck(res) {
      if (res.msg) {
        this.Helper.showValidateMsg("name", this.errorMsg, res.msg);
        this.Helper.showValidateMsg("code", this.errorMsg, res.msg);
        this.Helper.showValidateMsg("address", this.errorMsg, res.msg);
        this.Helper.showValidateMsg("personLiableId", this.errorMsg, res.msg);
        this.Helper.showValidateMsg("contactPhone", this.errorMsg, res.msg);
        this.Helper.showValidateMsg("status", this.errorMsg, res.msg);
        this.Helper.showValidateMsg("type", this.errorMsg, res.type);
        this.Helper.showValidateMsg("description", this.errorMsg, res.msg);
      }
    },

    // 手机号验证
    validatePhone(rule, value, callback) {
      if (!value) {
        callback(new Error("手机号码不能为空"));
      } else {
        const reg = /^1[3456789]\d{9}$/;
        if (reg.test(value)) {
          callback();
        } else {
          return callback(new Error("请输入正确的手机号"));
        }
      }
    },
  },
};
</script>
